package com.mm.cloth.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import java.util.ArrayList;
import java.util.List;

public class WatermarkRemovalCanvasView extends View {
    private static final String TAG = "WatermarkRemovalCanvasView";

    private Bitmap originalBitmap;
    private Bitmap maskBitmap;
    private Canvas maskCanvas;
    private Paint maskPaint;
    private Paint previewPaint;
    private Paint brushPaint;
    
    private Path currentPath;
    private List<PathInfo> pathHistory;
    private int historyIndex;
    
    private float brushSize = 20f;
    private RectF imageRect;
    
    private float lastX, lastY;
    private static final float TOUCH_TOLERANCE = 4;
    
    private OnPreviewUpdateListener previewUpdateListener;
    
    public interface OnPreviewUpdateListener {
        void onPreviewUpdate(Bitmap bitmap);
    }
    
    private static class PathInfo {
        Path path;
        float brushSize;

        PathInfo(Path path, float brushSize) {
            this.path = new Path(path);
            this.brushSize = brushSize;
        }
    }
    
    public WatermarkRemovalCanvasView(Context context) {
        super(context);
        init();
    }
    
    public WatermarkRemovalCanvasView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }
    
    public WatermarkRemovalCanvasView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }
    
    private void init() {
        pathHistory = new ArrayList<>();
        historyIndex = -1;
        imageRect = new RectF();
        
        // 初始化画笔
        maskPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        maskPaint.setStyle(Paint.Style.STROKE);
        maskPaint.setStrokeJoin(Paint.Join.ROUND);
        maskPaint.setStrokeCap(Paint.Cap.ROUND);
        maskPaint.setDither(true);
        maskPaint.setFilterBitmap(true);
        
        previewPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        previewPaint.setFilterBitmap(true);
        
        brushPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        brushPaint.setColor(0x80FF6B9D); // 透明仙女粉色 (50% 透明度)
        brushPaint.setStyle(Paint.Style.STROKE);
        brushPaint.setStrokeJoin(Paint.Join.ROUND);
        brushPaint.setStrokeCap(Paint.Cap.ROUND);
        brushPaint.setStrokeWidth(2f);
        brushPaint.setDither(true);
        
        currentPath = new Path();
    }
    
    public void setImageBitmap(Bitmap bitmap) {
        if (bitmap == null) return;
        
        originalBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, false);
        
        // 创建遮罩位图
        maskBitmap = Bitmap.createBitmap(originalBitmap.getWidth(), 
                originalBitmap.getHeight(), Bitmap.Config.ARGB_8888);
        maskCanvas = new Canvas(maskBitmap);
        maskCanvas.drawColor(Color.TRANSPARENT);
        
        // 计算图片在View中的显示区域
        calculateImageRect();
        
        // 清空历史记录
        pathHistory.clear();
        historyIndex = -1;
        
        invalidate();
    }
    
    private void calculateImageRect() {
        if (originalBitmap == null) return;
        
        float viewWidth = getWidth();
        float viewHeight = getHeight();
        float imageWidth = originalBitmap.getWidth();
        float imageHeight = originalBitmap.getHeight();
        
        float scale = Math.min(viewWidth / imageWidth, viewHeight / imageHeight);
        
        float scaledWidth = imageWidth * scale;
        float scaledHeight = imageHeight * scale;
        
        float left = (viewWidth - scaledWidth) / 2;
        float top = (viewHeight - scaledHeight) / 2;
        
        imageRect.set(left, top, left + scaledWidth, top + scaledHeight);
    }
    
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        calculateImageRect();
    }
    
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        
        if (originalBitmap == null) {
            // 绘制提示文字
            Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
            textPaint.setColor(Color.GRAY);
            textPaint.setTextSize(48f);
            textPaint.setTextAlign(Paint.Align.CENTER);
            canvas.drawText("点击选择图片开始去水印", getWidth() / 2f, getHeight() / 2f, textPaint);
            return;
        }
        
        // 绘制原图
        canvas.drawBitmap(originalBitmap, null, imageRect, previewPaint);
        
        // 绘制遮罩效果（将白色遮罩转换为透明淡粉色显示）
        if (maskBitmap != null) {
            Paint maskDisplayPaint = new Paint();
            maskDisplayPaint.setColorFilter(new android.graphics.ColorMatrixColorFilter(new float[]{
                0, 0, 0, 0, 255,  // 红色通道：输出255（仙女粉的红色分量）
                0, 0, 0, 0, 107,  // 绿色通道：输出107（仙女粉的绿色分量）
                0, 0, 0, 0, 157,  // 蓝色通道：输出157（仙女粉的蓝色分量）
                1, 0, 0, 0, 0     // Alpha通道：保持原始Alpha
            }));
            maskDisplayPaint.setAlpha(80); // 更透明的效果 (约30%透明度)
            canvas.drawBitmap(maskBitmap, null, imageRect, maskDisplayPaint);
        }
        
        // 绘制当前路径（固定为透明仙女粉色标记模式）
        if (!currentPath.isEmpty()) {
            brushPaint.setColor(0x80FF6B9D); // 透明仙女粉色 (50% 透明度)
            brushPaint.setStrokeWidth(brushSize * getScaleFactor());
            canvas.drawPath(currentPath, brushPaint);
        }
    }
    
    private float getScaleFactor() {
        if (originalBitmap == null) return 1f;
        return imageRect.width() / originalBitmap.getWidth();
    }
    
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (originalBitmap == null) return false;
        
        float x = event.getX();
        float y = event.getY();
        
        // 检查触摸点是否在图片区域内
        if (!imageRect.contains(x, y)) {
            return false;
        }
        
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                currentPath.reset();
                currentPath.moveTo(x, y);
                lastX = x;
                lastY = y;
                break;
                
            case MotionEvent.ACTION_MOVE:
                float dx = Math.abs(x - lastX);
                float dy = Math.abs(y - lastY);
                
                // 使用二次贝塞尔曲线使路径更平滑
                if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
                    currentPath.quadTo(lastX, lastY, (x + lastX) / 2, (y + lastY) / 2);
                    lastX = x;
                    lastY = y;
                    invalidate();
                }
                break;
                
            case MotionEvent.ACTION_UP:
                currentPath.lineTo(lastX, lastY);
                // 将当前路径添加到历史记录
                addPathToHistory();
                // 应用路径到遮罩
                applyPathToMask();
                currentPath.reset();
                invalidate();
                break;
        }
        
        return true;
    }
    
    private void addPathToHistory() {
        // 移除当前索引之后的历史记录
        while (pathHistory.size() > historyIndex + 1) {
            pathHistory.remove(pathHistory.size() - 1);
        }
        
        // 添加新路径（固定为标记模式）
        pathHistory.add(new PathInfo(currentPath, brushSize));
        historyIndex++;
        
        // 限制历史记录数量
        if (pathHistory.size() > 50) {
            pathHistory.remove(0);
            historyIndex--;
        }
    }
    
    private void applyPathToMask() {
        if (maskCanvas == null) return;
        
        // 将View坐标转换为Bitmap坐标
        Path bitmapPath = convertViewPathToBitmapPath(currentPath);
        
        maskPaint.setStrokeWidth(brushSize);

        // 固定为标记模式：绘制白色遮罩
        maskPaint.setColor(Color.WHITE);
        maskPaint.setXfermode(null);
        
        maskCanvas.drawPath(bitmapPath, maskPaint);
    }
    
    private Path convertViewPathToBitmapPath(Path viewPath) {
        Path bitmapPath = new Path();
        
        float scaleX = originalBitmap.getWidth() / imageRect.width();
        float scaleY = originalBitmap.getHeight() / imageRect.height();
        
        android.graphics.Matrix matrix = new android.graphics.Matrix();
        matrix.setTranslate(-imageRect.left, -imageRect.top);
        matrix.postScale(scaleX, scaleY);
        
        viewPath.transform(matrix, bitmapPath);
        return bitmapPath;
    }
    
    public void setBrushSize(float size) {
        this.brushSize = size;
    }
    
    public void undo() {
        if (historyIndex >= 0) {
            historyIndex--;
            redrawMask();
            invalidate();
        }
    }
    
    public void redo() {
        if (historyIndex < pathHistory.size() - 1) {
            historyIndex++;
            redrawMask();
            invalidate();
        }
    }
    
    public void clearMask() {
        if (maskCanvas != null) {
            maskCanvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
            pathHistory.clear();
            historyIndex = -1;
            invalidate();
        }
    }
    
    private void redrawMask() {
        if (maskCanvas == null) return;
        
        // 清空遮罩
        maskCanvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
        
        // 重新绘制历史路径（固定为标记模式）
        for (int i = 0; i <= historyIndex; i++) {
            PathInfo pathInfo = pathHistory.get(i);
            Path bitmapPath = convertViewPathToBitmapPath(pathInfo.path);

            maskPaint.setStrokeWidth(pathInfo.brushSize);
            maskPaint.setColor(Color.WHITE);
            maskPaint.setXfermode(null);

            maskCanvas.drawPath(bitmapPath, maskPaint);
        }
    }
    
    public boolean hasMarkedAreas() {
        return pathHistory.size() > 0;
    }

    /**
     * 获取遮罩图像
     * @return 遮罩Bitmap，白色区域为标记区域
     */
    public Bitmap getMaskBitmap() {
        if (originalBitmap == null) {
            Log.e(TAG, "原始图像为空，无法生成遮罩");
            return null;
        }

        // 如果没有标记区域，返回全黑遮罩
        if (pathHistory.isEmpty()) {
            Log.d(TAG, "没有标记区域，返回全黑遮罩");
            Bitmap blackMask = Bitmap.createBitmap(originalBitmap.getWidth(), originalBitmap.getHeight(), Bitmap.Config.ARGB_8888);
            blackMask.eraseColor(Color.BLACK);
            return blackMask;
        }

        // 创建白色遮罩（LaMa需要白色区域表示需要修复的区域）
        Bitmap whiteMask = Bitmap.createBitmap(originalBitmap.getWidth(), originalBitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas whiteCanvas = new Canvas(whiteMask);
        whiteCanvas.drawColor(Color.BLACK); // 背景为黑色

        // 将标记区域绘制为白色
        Paint whitePaint = new Paint();
        whitePaint.setColor(Color.WHITE);
        whitePaint.setStyle(Paint.Style.STROKE);
        whitePaint.setStrokeWidth(brushSize);
        whitePaint.setStrokeCap(Paint.Cap.ROUND);
        whitePaint.setStrokeJoin(Paint.Join.ROUND);
        whitePaint.setAntiAlias(true);

        // 绘制所有路径
        for (PathInfo pathInfo : pathHistory) {
            whiteCanvas.drawPath(pathInfo.path, whitePaint);
        }

        Log.d(TAG, "生成遮罩图像: " + whiteMask.getWidth() + "x" + whiteMask.getHeight());

        return whiteMask;
    }
    
    public Bitmap processWatermarkRemoval() {
        if (originalBitmap == null) return null;

        // 如果没有标记区域，直接返回原图
        if (pathHistory.isEmpty()) {
            return originalBitmap.copy(Bitmap.Config.ARGB_8888, true);
        }

        // 确保遮罩存在并且是最新的
        if (maskBitmap == null) {
            maskBitmap = Bitmap.createBitmap(originalBitmap.getWidth(),
                    originalBitmap.getHeight(), Bitmap.Config.ARGB_8888);
            maskCanvas = new Canvas(maskBitmap);
            maskCanvas.drawColor(Color.TRANSPARENT);
        }

        // 重新绘制遮罩确保是最新状态
        redrawMask();

        // 执行去水印算法
        return simpleInpainting(originalBitmap, maskBitmap);
    }
    
    private Bitmap simpleInpainting(Bitmap original, Bitmap mask) {
        // 增强的修复算法：使用周围像素的平均值填充
        Bitmap result = original.copy(Bitmap.Config.ARGB_8888, true);
        int width = result.getWidth();
        int height = result.getHeight();

        int processedPixels = 0; // 统计处理的像素数量

        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                int maskPixel = mask.getPixel(x, y);

                // 检查是否为白色遮罩像素（需要修复的区域）
                int maskR = (maskPixel >> 16) & 0xff;
                int maskG = (maskPixel >> 8) & 0xff;
                int maskB = maskPixel & 0xff;
                int maskAlpha = (maskPixel >> 24) & 0xff;

                // 如果是白色像素或有Alpha值，说明需要修复
                if (maskAlpha > 0 || (maskR > 200 && maskG > 200 && maskB > 200)) {
                    int newColor = getAverageColor(original, x, y, 5); // 增大采样半径
                    result.setPixel(x, y, newColor);
                    processedPixels++;
                }
            }
        }

        // 如果没有处理任何像素，可能是遮罩问题
        android.util.Log.d("WatermarkRemoval", "Processed pixels: " + processedPixels);

        return result;
    }
    
    private int getAverageColor(Bitmap bitmap, int centerX, int centerY, int radius) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();

        int totalR = 0, totalG = 0, totalB = 0, count = 0;

        // 扩大采样范围，获取更好的修复效果
        for (int y = Math.max(0, centerY - radius); y <= Math.min(height - 1, centerY + radius); y++) {
            for (int x = Math.max(0, centerX - radius); x <= Math.min(width - 1, centerX + radius); x++) {
                // 跳过中心区域，避免采样到水印像素
                double distance = Math.sqrt((x - centerX) * (x - centerX) + (y - centerY) * (y - centerY));
                if (distance < 2) continue; // 跳过中心2像素范围

                int pixel = bitmap.getPixel(x, y);
                totalR += (pixel >> 16) & 0xff;
                totalG += (pixel >> 8) & 0xff;
                totalB += pixel & 0xff;
                count++;
            }
        }

        // 如果没有找到合适的像素，尝试更大范围
        if (count == 0) {
            for (int y = Math.max(0, centerY - radius * 2); y <= Math.min(height - 1, centerY + radius * 2); y++) {
                for (int x = Math.max(0, centerX - radius * 2); x <= Math.min(width - 1, centerX + radius * 2); x++) {
                    double distance = Math.sqrt((x - centerX) * (x - centerX) + (y - centerY) * (y - centerY));
                    if (distance < radius) continue; // 跳过内圈

                    int pixel = bitmap.getPixel(x, y);
                    totalR += (pixel >> 16) & 0xff;
                    totalG += (pixel >> 8) & 0xff;
                    totalB += pixel & 0xff;
                    count++;

                    if (count >= 10) break; // 获取足够样本即可
                }
                if (count >= 10) break;
            }
        }

        if (count == 0) return bitmap.getPixel(centerX, centerY);

        int avgR = Math.min(255, Math.max(0, totalR / count));
        int avgG = Math.min(255, Math.max(0, totalG / count));
        int avgB = Math.min(255, Math.max(0, totalB / count));

        return Color.rgb(avgR, avgG, avgB);
    }
    
    public void setOnPreviewUpdateListener(OnPreviewUpdateListener listener) {
        this.previewUpdateListener = listener;
    }

    /**
     * 生成带有遮罩的图片，用于API上传
     * @return 合成后的带遮罩图片
     */
    public Bitmap generateMaskedImage() {
        if (originalBitmap == null) return null;

        // 创建结果位图
        Bitmap result = originalBitmap.copy(Bitmap.Config.ARGB_8888, true);
        Canvas canvas = new Canvas(result);

        // 绘制遮罩效果（白色遮罩表示需要去除的区域）
        if (maskBitmap != null) {
            Paint maskPaint = new Paint();
            maskPaint.setColor(Color.WHITE);
            maskPaint.setAlpha(255); // 完全不透明的白色遮罩
            canvas.drawBitmap(maskBitmap, 0, 0, maskPaint);
        }

        return result;
    }

    // 强制去水印方法，确保有明显效果
    public Bitmap forceWatermarkRemoval() {
        if (originalBitmap == null) return null;

        // 如果没有标记区域，直接返回原图
        if (pathHistory.isEmpty()) {
            return originalBitmap.copy(Bitmap.Config.ARGB_8888, true);
        }

        // 创建结果位图
        Bitmap result = originalBitmap.copy(Bitmap.Config.ARGB_8888, true);
        int width = result.getWidth();
        int height = result.getHeight();

        // 确保遮罩存在
        if (maskBitmap == null) {
            maskBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            maskCanvas = new Canvas(maskBitmap);
            maskCanvas.drawColor(Color.TRANSPARENT);
        }

        // 重新绘制遮罩
        redrawMask();

        int processedPixels = 0;

        // 多次迭代修复，获得更好效果
        for (int iteration = 0; iteration < 3; iteration++) {
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    int maskPixel = maskBitmap.getPixel(x, y);

                    // 检查是否为需要修复的区域
                    int maskR = (maskPixel >> 16) & 0xff;
                    int maskG = (maskPixel >> 8) & 0xff;
                    int maskB = maskPixel & 0xff;
                    int maskAlpha = (maskPixel >> 24) & 0xff;

                    if (maskAlpha > 0 || (maskR > 200 && maskG > 200 && maskB > 200)) {
                        // 使用更强的修复算法
                        int newColor = getEnhancedAverageColor(result, x, y, 6);
                        result.setPixel(x, y, newColor);
                        processedPixels++;
                    }
                }
            }
        }

        android.util.Log.d("WatermarkRemoval", "Force processed pixels: " + processedPixels);
        return result;
    }

    // 增强的颜色平均算法
    private int getEnhancedAverageColor(Bitmap bitmap, int centerX, int centerY, int radius) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();

        int totalR = 0, totalG = 0, totalB = 0, count = 0;

        // 使用加权平均，距离越近权重越大
        for (int y = Math.max(0, centerY - radius); y <= Math.min(height - 1, centerY + radius); y++) {
            for (int x = Math.max(0, centerX - radius); x <= Math.min(width - 1, centerX + radius); x++) {
                double distance = Math.sqrt((x - centerX) * (x - centerX) + (y - centerY) * (y - centerY));
                if (distance < 3) continue; // 跳过中心区域
                if (distance > radius) continue; // 超出半径

                int pixel = bitmap.getPixel(x, y);
                double weight = 1.0 / (1.0 + distance); // 距离权重

                totalR += ((pixel >> 16) & 0xff) * weight;
                totalG += ((pixel >> 8) & 0xff) * weight;
                totalB += (pixel & 0xff) * weight;
                count += weight;
            }
        }

        if (count == 0) {
            // 如果没有找到合适像素，使用简单平均
            return getAverageColor(bitmap, centerX, centerY, radius);
        }

        int avgR = Math.min(255, Math.max(0, (int)(totalR / count)));
        int avgG = Math.min(255, Math.max(0, (int)(totalG / count)));
        int avgB = Math.min(255, Math.max(0, (int)(totalB / count)));

        return Color.rgb(avgR, avgG, avgB);
    }
}
